package com.stox.services.indicator.manager.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.stox.services.data.provider.manager.BarManager;
import com.stox.services.indicator.manager.IndicatorManager;
import com.stox.services.indicator.model.intf.Indicator;
import com.stox.shared.indicator.model.IndicatorBeanDescriptor;
import com.stox.shared.model.filter.BarCriteria;

@Component
public class IndicatorManagerImpl implements IndicatorManager, InitializingBean {

	@Autowired
	private BarManager barManager;
	
	@Autowired
	private ApplicationContext applicationContext;
	
	private final Map<String,Indicator<Object,Object>> cache = new HashMap<>();
	private final List<IndicatorBeanDescriptor> indicatorInfos = new ArrayList<>();
	
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void afterPropertiesSet() throws Exception {
		Collection<Indicator> indicators = applicationContext.getBeansOfType(Indicator.class).values();
		for(Indicator<Object,Object> indicator : indicators){
			cache.put(indicator.getIndicatorBeanDescriptor().getKey(), indicator);
			indicatorInfos.add(indicator.getIndicatorBeanDescriptor());
		}
	}
	
	public List<IndicatorBeanDescriptor> findAll(){
		return indicatorInfos;
	}
	
	public Object[] getValues(IndicatorBeanDescriptor indicatorInfo, BarCriteria barCriteria){
		Indicator<Object, Object> indicator = cache.get(indicatorInfo.getKey());
		return indicator.getValues(indicatorInfo.createBean(), barManager.find(barCriteria));
	}
	
}
